// API配置文件
const API_CONFIG = {
  // 后端服务器地址 - 根据实际后端服务器配置
  BASE_URL: 'http://localhost:1001', // 后端服务器地址
  
  // 开发模式配置 - 关闭模拟模式，使用真实API
  DEV_MODE: false, // 关闭开发模式，使用真实后端API
  
  // API端点
  ENDPOINTS: {
    LOGIN: '/wxUser/login', // 微信用户登录接口
    // 可以在这里添加其他API端点
    WRONG_QUERY: '/wrong/getUserId', // 根据用户ID与科目查询错题
    WRONG_DETAIL: '/wrong/getById', // 根据题目ID查询详情
    WRONG_ADD: '/wrong/add', // 仅保存四个字段的错题添加
    BOOK_ISBN: '/books/isbn' // 根据ISBN-13查询图书
  },
  
  // 请求超时时间（毫秒）
  TIMEOUT: 10000,
  
  // 请求头配置
  HEADERS: {
    'content-type': 'application/json'
  }
};

// 通用请求方法
const request = (options) => {
  return new Promise((resolve, reject) => {
    const {
      url,
      method = 'GET',
      data = {},
      header = {},
      timeout = API_CONFIG.TIMEOUT
    } = options;

    // 构建完整URL
    const fullUrl = url.startsWith('http') ? url : API_CONFIG.BASE_URL + url;

    console.log('发起API请求:', {
      url: fullUrl,
      method: method,
      data: data
    });

    wx.request({
      url: fullUrl,
      method: method,
      data: data,
      header: {
        ...API_CONFIG.HEADERS,
        ...header
      },
      timeout: timeout,
      success: (res) => {
        console.log('API请求成功:', fullUrl, res);
        
        // 统一处理响应
        if (res.statusCode === 200) {
          // 检查后端返回的数据结构
          if (res.data && typeof res.data === 'object') {
            resolve(res.data);
          } else {
            resolve({
              code: 200,
              message: '请求成功',
              data: res.data
            });
          }
        } else {
          // 处理HTTP错误状态码
          let errorMessage = '请求失败';
          switch (res.statusCode) {
            case 400:
              errorMessage = '请求参数错误，请检查输入信息';
              break;
            case 401:
              errorMessage = '未授权访问，请重新登录';
              break;
            case 403:
              errorMessage = '访问被拒绝，权限不足';
              break;
            case 404:
              errorMessage = '请求的服务不存在';
              break;
            case 500:
              errorMessage = '服务器内部错误，请稍后重试';
              break;
            case 502:
              errorMessage = '网关错误，服务暂时不可用';
              break;
            case 503:
              errorMessage = '服务暂时不可用，请稍后重试';
              break;
            default:
              errorMessage = `HTTP错误: ${res.statusCode}`;
          }
          
          reject({
            code: res.statusCode,
            message: errorMessage,
            data: res.data
          });
        }
      },
      fail: (error) => {
        console.error('API请求失败:', fullUrl, error);
        
        // 分析错误类型并提供友好提示
        let errorMessage = '网络连接异常';
        let errorCode = -1;
        
        if (error.errMsg) {
          if (error.errMsg.includes('timeout')) {
            errorMessage = '请求超时，请检查网络连接后重试';
            errorCode = -2;
          } else if (error.errMsg.includes('fail')) {
            if (error.errMsg.includes('url not in domain list')) {
              errorMessage = '网络请求被限制，请在微信开发者工具中关闭域名校验';
              errorCode = -3;
            } else if (error.errMsg.includes('network error')) {
              errorMessage = '网络连接失败，请检查网络设置';
              errorCode = -4;
            } else if (error.errMsg.includes('server unreachable')) {
              errorMessage = '无法连接到服务器，请确认服务器是否正常运行';
              errorCode = -5;
            } else {
              errorMessage = '网络请求失败，请稍后重试';
            }
          }
        }
        
        reject({
          code: errorCode,
          message: errorMessage,
          error: error,
          originalError: error.errMsg
        });
      }
    });
  });
};

// 登录API
const loginAPI = {
  // 微信登录 - 根据后端接口结构调整参数
  wechatLogin: (code, nickname, avatarUrl) => {
    console.log('调用微信登录API:', { code, nickname, avatarUrl });
    
    // 参数验证
    if (!code) {
      return Promise.reject({
        code: -100,
        message: '微信授权码不能为空',
        data: null
      });
    }
    
    // 根据后端接口要求构建请求参数
    const requestData = {
      code: code,
      nickname: nickname || '',
      avatarUrl: avatarUrl || ''
    };

    return request({
      url: API_CONFIG.ENDPOINTS.LOGIN,
      method: 'POST',
      data: requestData
    }).then(response => {
      console.log('登录API响应:', response);
      
      // 根据后端返回的数据结构进行处理
      // 假设后端返回格式为: { code: 200, msg: "登录成功", data: {...} }
      if (response.code === 200) {
        return {
          code: 200,
          message: response.msg || '登录成功',
          data: response.data
        };
      } else {
        throw {
          code: response.code || 500,
          message: response.msg || '登录失败',
          data: response.data
        };
      }
    }).catch(error => {
      console.error('登录API错误:', error);
      
      // 增强错误处理
      if (error.code === -3) {
        // 域名校验错误的特殊处理
        throw {
          code: -3,
          message: '请在微信开发者工具中关闭"不校验合法域名"选项，或配置合法域名',
          data: null,
          suggestion: '开发者工具 -> 详情 -> 本地设置 -> 不校验合法域名、web-view（业务域名）、TLS 版本以及 HTTPS 证书'
        };
      } else if (error.code === -5) {
        // 服务器连接错误
        throw {
          code: -5,
          message: '无法连接到后端服务器，请确认服务器在 http://localhost:1001 正常运行',
          data: null,
          suggestion: '请检查后端服务是否启动，端口是否正确'
        };
      }
      
      throw error;
    });
  }
};

// 错题查询API
const wrongQuestionsAPI = {
  // 根据用户ID与科目名称查询错题列表（科目可为空表示全部）
  queryByUserIdAndSubject: (userId, subjectName) => {
    if (!userId) {
      return Promise.reject({
        code: -100,
        message: '用户ID不能为空',
        data: null
      });
    }

    const requestData = {
      userId: userId,
      subjectName: subjectName || null
    };

    return request({
      url: API_CONFIG.ENDPOINTS.WRONG_QUERY,
      method: 'POST',
      data: requestData
    }).then(response => {
      // 兼容不同返回格式：{code, msg, data} 或 直接数组
      if (response && response.code === 200) {
        return response.data || [];
      }
      if (Array.isArray(response)) {
        return response;
      }
      if (response && response.data) {
        return response.data;
      }
      throw {
        code: response?.code || 500,
        message: response?.msg || response?.message || '查询失败',
        data: response?.data
      };
    });
  },

  // 根据题目ID查询详情
  getById: (id) => {
    if (!id && id !== 0) {
      return Promise.reject({
        code: -100,
        message: '题目ID不能为空',
        data: null
      });
    }
    return request({
      url: API_CONFIG.ENDPOINTS.WRONG_DETAIL,
      method: 'GET',
      data: { id }
    }).then(response => {
      // 兼容不同返回格式
      const payload = (response && response.data) ? response.data : response;
      const ok = (response && (response.code === 200 || response.status === 'ok')) || Array.isArray(response) || typeof response === 'object';
      if (!ok) {
        throw {
          code: response?.code || 500,
          message: response?.msg || response?.message || '查询失败',
          data: response?.data
        };
      }
      const q = Array.isArray(payload) ? payload[0] : payload;
      if (!q) return null;
      // 字段归一化 + 富文本兼容
      const toRich = (str) => {
        if (!str) return '';
        const s = String(str);
        const looksLikeHtml = /<[^>]+>/.test(s);
        return looksLikeHtml ? s : s.replace(/\r?\n/g, '<br/>');
      };
      const normalized = {
        id: q.id ?? q.questionId ?? q.qid ?? q.wid ?? null,
        number: q.number ?? q.num ?? q.order ?? q.index ?? 1,
        type: q.type ?? q.questionType ?? q.category ?? q.kind ?? q.question_type ?? '',
        content: q.content ?? q.contentHtml ?? q.html ?? q.title ?? q.text ?? q.stem ?? q.question ?? q.questionContent ?? q.question_content ?? q.desc ?? '',
        solution: q.solution ?? q.solutionHtml ?? q.answer ?? q.correctAnswer ?? q.correct_answer ?? q.explanation ?? q.analysis ?? q.resolve ?? '',
        subject: q.subject ?? q.subjectName ?? q.subject_name ?? q.subjectZh ?? '',
        grade: q.grade ?? q.gradeName ?? q.grade_name ?? q.gradeZh ?? '',
        difficulty: q.difficulty ?? q.level ?? q.difficultyLevel ?? '',
        status: q.status ?? ((q.is_mastered ?? q.isMastered ?? q.mastered) ? 'mastered' : 'unmastered'),
        hasVideo: q.hasVideo ?? q.video ?? q.has_video ?? false,
        date: q.date ?? q.wrongTime ?? q.wrong_time ?? q.createTime ?? q.create_time ?? q.createdAt ?? q.updatedAt ?? q.updated_at ?? q.created_at ?? '',
        options: q.options ?? null,
        userAnswer: q.userAnswer ?? q.user_answer ?? null,
        // 新增错因映射，兼容多种命名
        reason: q.reason ?? q.errorReason ?? q.wrongReason ?? q.wrong_reason ?? q.cause ?? q.errorCause ?? ''
      };
      normalized.content = toRich(normalized.content);
      normalized.solution = toRich(normalized.solution);
      // 新增：错因富文本处理
      normalized.reason = toRich(normalized.reason);
      return normalized;
    });
  }
};

// 错题新增API（仅四个字段）
const wrongAPI = {
  addWrongQuestion: (payload) => {
    const data = {
      questionContent: payload?.questionContent || '',
      userAnswer: payload?.userAnswer || '',
      correctAnswer: payload?.correctAnswer || '',
      reason: payload?.reason || ''
    };

    return request({
      url: API_CONFIG.ENDPOINTS.WRONG_ADD,
      method: 'POST',
      data
    }).then(response => {
      // 兼容 Result<T> 响应结构：{ code:200, msg:"成功", data: <id> }
      if (response && response.code === 200) {
        return response.data ?? true;
      }
      throw {
        code: response?.code || 500,
        message: response?.msg || response?.message || '添加失败',
        data: response?.data
      };
    });
  }
};

// 图书查询API
const bookAPI = {
  // 根据ISBN-13查询图书（后端：GET /books/isbn/{isbn13}）
  getByIsbn: (isbn13) => {
    if (!isbn13) {
      return Promise.reject({ code: -100, message: 'ISBN不能为空' });
    }
    // 简单校验：13位且以978/979开头
    const valid = typeof isbn13 === 'string' && isbn13.length === 13 && (isbn13.startsWith('978') || isbn13.startsWith('979'));
    if (!valid) {
      return Promise.reject({ code: -101, message: 'ISBN格式不正确，应为以978/979开头的13位数字' });
    }

    return request({
      url: `${API_CONFIG.ENDPOINTS.BOOK_ISBN}/${isbn13}`,
      method: 'GET'
    }).then(response => {
      if (response && response.code === 200 && response.data) {
        return response; // { code:200, data: TbBook }
      }
      throw {
        code: response?.code || 500,
        message: response?.msg || response?.message || '查询失败',
        data: response?.data
      };
    });
  }
};

// 导出API方法
module.exports = {
  API_CONFIG,
  request,
  loginAPI,
  wrongQuestionsAPI,
  wrongAPI,
  bookAPI
};